#Makefile rules

ENVDIR	= /usr/bin
DEPDIR = .deps

PATH    = $(ENVDIR):/usr/sbin:/usr/bin:/sbin:/bin:
CC	= $(ENVDIR)/gcc
AR      = $(ENVDIR)/ar
RANLIB  = $(ENVDIR)/ranlib

.PHONY: all
all: $(DEPDIR) subdirs $(TARGET) $(TARGET1) $(TARGET_A) 

subdirs:
ifdef	SUBDIRS
	@for i in $(SUBDIRS); do \
	    echo "===>compile $(PWD)/$$i"; \
	    if [ -f "$$i/Makefile" ]; then \
	        (cd $$i && $(MAKE) all) || exit 1; \
	    fi; \
	done
endif


.PHONY: depclean
depclean :
ifdef	SUBDIRS
	@for i in $(SUBDIRS); do \
	    echo "===>depclean $(PWD)/$$i"; \
	    if [ -f "$$i/Makefile" ]; then \
	        (cd $$i && $(MAKE) depclean) || exit 1; \
	    fi; \
	done
endif
	@-rm -rf *.o *.d $(TARGETS) $(TARGET_OBJS)
	@-rm -rf $(DEPDIR)

# clean rules
.PHONY: clean
clean: 
ifdef	SUBDIRS
	@for i in $(SUBDIRS); do \
	    echo "===>clean $(PWD)/$$i"; \
	    if [ -f "$$i/Makefile" ]; then \
	        (cd $$i && $(MAKE) clean) || exit 1; \
	    fi; \
	done
endif
	@-rm -rf *.o *.d $(TARGETS) $(TARGET1) $(TARGET_OBJS)


$(DEPDIR): 
	+@[ -d $@ ] || mkdir -p $@

%.o: %.c 
	$(CC) $(CFLAGS) -c $< -o $@ -MD -MF $(DEPDIR)/$(<:.c=.d)

#%.o: %.c
#$(CC) $(CFLAGS) -c $< -o $@ -MD -MF $(@:.o=.d)
#@cp $*.d $(DEPDIR)/$*.d
#@sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \
#    -e '/^$$/ d' -e 's/$$/ :/' < $*.d >> $(DEPDIR)/$*.d;
#@-rm -f $*.d

$(TARGET): $(TARGET_OBJS)
	$(CC) -o $@ $^ $(LDFLAGS) $(TARGET_LIBS)
$(TARGET1): $(TARGET_OBJS1)
	$(CC) -o $@ $^ $(LDFLAGS) $(TARGET_LIBS1)

$(TARGET_A): $(TARGET_OBJS_A)
	@echo "\tAR\t$@"
	$(AR) rc $@ $^
	$(RANLIB) $@
ifdef LIBDIR
	-rm -rf $(LIBDIR)/$(TARGET_A)
	-mkdir -p $(LIBDIR)
	-cp $@ $(LIBDIR)/$(TARGET_A)
endif


-include $(DEPDIR)/*.d




